import React, { PureComponent } from 'react';
import { connect } from 'dva';

import {
  List,
  Avatar,
  Card,
  Button,
  Form,
  Input,
  Modal,
  Select,
  InputNumber,
  Popconfirm,
  Radio,
  Table,
} from 'antd';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from './styles.less';

const { Item: FormItem } = Form;
const { Button: RadioButton, Group: RadioGroup } = Radio;
const { Option } = Select;
const { TextArea, Search } = Input;


const ModelName = 'relationer';

@connect(({ loading, relationer }) => ({
  loading: loading.effects[`${ModelName}`],
  model: relationer,
}))
@Form.create()
class Comp extends PureComponent {
  state = {
    visible: false,
    keyword: '',
    current: {},
    currentType: 1,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: `${ModelName}/get`,
    });
  }

  showModal = () => {
    this.setState({
      visible: true,
      current: undefined,
    });
  };

  showEditModal = item => {
    this.setState({
      visible: true,
      current: item,
    });
  };

  handleCancel = () => {
    this.setState({
      visible: false,
    });
  };

  handleSubmit = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    const { current } = this.state;
    const id = current ? current.id : 0;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const payload = {
        id,
        ...fieldsValue,
        objectName: fieldsValue.objectName.trim(),
      };
      dispatch({
        type: `${ModelName}/createOrUpdate`,
        payload: payload,
        callback: _ => {
          this.setState({ visible: false });
        },
      });
    });
  };

  deleteItem = id => {
    const { dispatch } = this.props;
    dispatch({
      type: `${ModelName}/remove`,
      payload: id,
    });
  };

  render() {
    const {
      model,
      loading,
      form: { getFieldDecorator },
    } = this.props;
    const { visible, keyword, current } = this.state;
    const { list } = model;

    let dSource = list;

    if (dSource && Array.isArray(dSource) && dSource.length > 0) {
      dSource = keyword ? dSource.filter(r => r.objectName.toUpperCase().indexOf(keyword.toUpperCase()) >= 0 || (r.address && r.address.indexOf(keyword) >= 0)) : dSource;
    }
    const editForm = () => {
      const formLayout = {
        labelCol: { span: 3 },
        wrapperCol: { span: 19 },
      };

      return (
        <Modal
          title={`${current ? '编辑' : '添加'}${model.title}`}
          className={styles.standardListForm}
          destroyOnClose
          width={'90%'}
          visible={visible}
          onOk={this.handleSubmit}
          onCancel={this.handleCancel}
        >
          <Form onSubmit={this.handleSubmit}>
            <FormItem label="排序" {...formLayout}>
              {getFieldDecorator('sortIndex', {
                rules: [{ required: true, message: '请输入排序号' }],
                initialValue: current ? current.sortIndex : 0,
              })(<InputNumber />)}
            </FormItem>

            <FormItem label="名称" {...formLayout}>
              {getFieldDecorator('objectName', {
                rules: [{ required: true, message: '请输入名称' }],
                initialValue: current ? current.objectName : '',
              })(<Input placeholder="请输入" />)}
            </FormItem>
            <FormItem label="地址" {...formLayout}>
              {getFieldDecorator('address', {
                initialValue: current ? current.address : '',
              })(<TextArea rows={5} placeholder="客户地址" />)}
            </FormItem>

          </Form>
        </Modal>
      );
    };

    const testColumns = [
      {
        title: 'ID',
        dataIndex: 'id',
      },
    ];

    let columns = [
      {
        title: '序号',
        dataIndex: 'sortIndex',
        width: '100',
      },
      {
        title: '名称',
        dataIndex: 'objectName',
      },
      {
        title: '地址',
        width: 500,
        dataIndex: 'address',
      },
      {
        title: '',
        key: 'action',
        width: '100',
        render: (text, record) => (<span>
          <a onClick={() => this.showEditModal(record)}>编辑</a>
          <Popconfirm title="确定要删除此往来单位吗? 删除无法恢复!" onConfirm={() => this.deleteItem(record.id)}><a style={{ marginLeft: '4px' }}>删除</a></Popconfirm>
        </span>),
      },
    ];

    if (process.env.NODE_ENV !== 'production') {
      columns = testColumns.concat(columns);
    }

    const extraContent = (
      <div className={styles.extraContent}>
        <Search className={styles.extraContentSearch} placeholder="请输入名称查询" onSearch={(value) => this.setState({ keyword: value })} />
      </div>
    );

    return (
      <PageHeaderWrapper>
        <div className={styles.standardList}>
          <Card
            className={styles.listCard}
            bordered={false}
            title={<Button type="primary" onClick={this.showModal}>添加</Button>}
            extra={extraContent}
          >

            <Table
              bordered={true}
              key="id"
              rowKey="id"
              size="small"
              loading={loading}
              dataSource={dSource}
              columns={columns}
              pagination={{
                showSizeChanger: true,
                pageSize: 50,
              }}
            />
          </Card>
        </div>
        {editForm()}
      </PageHeaderWrapper>
    );
  }
}

export default Comp;
